#include "variablelist.h"
#include <Qt>
#include <QtGui>


//--- Debug ---
#include <iostream>
using namespace std;
//

VariableList::VariableList(QWidget *parent)
	:QTableView()
{
	this->setParent(parent);
	model = new QStandardItemModel(1,4,this);
	// --- Options on the display ---
		// -- Vertical Header
		Vertical=new QHeaderView(Qt::Vertical,this);
		Vertical->setHidden(true);
		this->setVerticalHeader(Vertical);
		
		// -- Horizontal Header
		
		Horizontal=new QHeaderView(Qt::Horizontal,this);
		Horizontal->setDefaultAlignment(Qt::AlignLeft);
		Horizontal->setStretchLastSection(true);
		this->setHorizontalHeader(Horizontal);
		

}
void VariableList::put(Variable *V)
{
	bool WasPresent=false;
	for (int i=0;i<List.size();++i){
		if(List.at(i).Name==V->Name){
			List.replace(i,*V);
			WasPresent=true;
		}
	}
	if (WasPresent == false){
		List.append(*V);
	}
	this->UpdateModel();
}

double VariableList::getValFromName(QString N,bool&OK){
	OK=false;
	double Val=0;
	int count=0;
	while(count<List.size()&&OK==false){
		if(List.at(count).Name==N){
			Val=List.at(count).Data;
			OK=true;
		}
		else count++;
	}
	return Val;
}

QString VariableList::getExprFromName(QString N,bool&OK){
	OK=false;
	QString Expr=NULL;
	int count=0;
	while(count<List.size()&&OK==false){
		if(List.at(count).Name==N){
			Expr=List.at(count).Expression;
			OK=true;
		}
		else count++;
	}
	return Expr;
}

void VariableList::remove(QString N){
	bool OK=false;
	int count=0;
	while(count<List.size()&&OK==false){
		if(List.at(count).Name==N){
			List.removeAt(count);
			OK=true;
		}
		else count++;
	}
	this->UpdateModel();
}

void VariableList::UpdateModel(){
	delete model;
	model = new QStandardItemModel(List.size(),4,this); 
	
	model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
	model->setHeaderData(1, Qt::Horizontal, QObject::tr("Name"));
	model->setHeaderData(2, Qt::Horizontal, QObject::tr("Value"));
	model->setHeaderData(3, Qt::Horizontal, QObject::tr("Expression"));
	
	for (int row = 0; row < List.size(); ++row){
		QStandardItem *item0=new QStandardItem;
		item0->setText(QString::number(row));
		item0->setEditable(false);
		model->setItem(row,0, item0);
		
		QStandardItem *item1=new QStandardItem;
		item1->setText(List.at(row).Name);
		item1->setEditable(false);
		model->setItem(row,1, item1);
		
		QStandardItem *item2=new QStandardItem;
		item2->setText(QString::number(List.at(row).Data));
		item2->setEditable(false);
		model->setItem(row,2, item2);
		
		QStandardItem *item3=new QStandardItem;
		item3->setText(List.at(row).Expression);
		item3->setEditable(false);
		model->setItem(row,3, item3);
	}
	this->setModel(model);
	
			// -- Horizontal Dimmensions
		this->setColumnWidth(0,25);
		this->setColumnWidth(1,100);
		this->setColumnWidth(2,100);
}


